package com.next.aappublicapp;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.gson.Gson;
import com.next.aap.messages.DeviceRegisteredMessage;
import com.next.aap.messages.FacebookUserRegisteredMessage;
import com.next.aap.messages.NewFacebookNotificationMessage;
import com.next.aap.messages.NotificationMessage;
import com.next.aappublicapp.util.GcmUtil;
import com.next.aappublicapp.util.PreferencesUtil;
import com.next.aappublicapp.util.UserProfileUtil;

public class AapBroadcastReceiver extends BroadcastReceiver {
    static final String TAG = "GCMDemo";
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context ctx;
    

    @Override
    public void onReceive(Context context, Intent intent) {
    	try{
    		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
            ctx = context;
            String messageType = gcm.getMessageType(intent);
            Log.i("Ravi", "messageType="+messageType);
            Log.i("Ravi", "intent.getExtras().toString()="+intent.getExtras().toString());
            Log.i("Ravi", "intent.getExtras().toString(msg)="+intent.getExtras().getString(NotificationMessage.MESSAGE));
            
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                //sendNotification("Send error: " + intent.getExtras().toString(),"Aam Aadmi Party",messageType,null);
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                //sendNotification("Deleted messages on server: " + intent.getExtras().toString(),"Aam Aadmi Party",messageType,null);
            } else {
                processNotfication(context, intent);
            }
    	}catch(Exception ex){
    		ex.printStackTrace();
    	}
        setResultCode(Activity.RESULT_OK);
        
    }
    private void processNotfication(Context context,Intent intent){
    	//giveVibratation(context);
    	String internalMessageType = intent.getExtras().getString(NotificationMessage.MESSAGE_TYPE);
    	String msg = intent.getExtras().getString(NotificationMessage.MESSAGE);
    	if(NotificationMessage.DEVICE_REGISTERED_MESSAGE.equals(internalMessageType)){
    		onDeviceRegistration(context, msg);
    	}else if(NotificationMessage.FACEBOOK_USER_REGISTERED_MESSAGE.equals(internalMessageType)){
    		onFacebookUserRegistration(context, msg);
    	}else if(NotificationMessage.NEW_FACEBOOK_MESSAGE.equals(internalMessageType)){
    		onNewFacebookMessage(context, msg,internalMessageType,context.getString(R.string.notifications_facebook_message),context.getString(R.string.notifications_facebook_message_vibrate));
    	}else if(NotificationMessage.NEW_NEWS_MESSAGE.equals(internalMessageType)){
    		onNewNewsMessage(context, msg, internalMessageType,context.getString(R.string.notifications_news_video_message));
    	}else if(NotificationMessage.NEW_VIDEO_MESSAGE.equals(internalMessageType)){
    		onNewVideoMessage(context, msg, internalMessageType,context.getString(R.string.notifications_news_video_message));
    	}else {
    		//sendNotification(msg,"Aam Aadmi Party",internalMessageType,null);
    		//dont do anything
    	}
    }
    private void onNewNewsMessage(Context context,String msg,String msgType,String ringtoneKey){
    	Log.i("Ravi", "New News message : "+msg);
		Gson gson = new Gson();
		NewFacebookNotificationMessage newFacebookNotificationMessage = gson.fromJson(msg, NewFacebookNotificationMessage.class);
		sendNotification(newFacebookNotificationMessage.getNotificationTitle(),"AAP News Update",msgType,ringtoneKey);
    }
    private void onNewVideoMessage(Context context,String msg,String msgType,String ringtoneKey){
    	Log.i("Ravi", "New Video message : "+msg);
		Gson gson = new Gson();
		NewFacebookNotificationMessage newFacebookNotificationMessage = gson.fromJson(msg, NewFacebookNotificationMessage.class);
		sendNotification(newFacebookNotificationMessage.getNotificationTitle(),"AAP Video Update",msgType,ringtoneKey);
    }
    private void onFacebookUserRegistration(Context context,String msg){
    	Log.i("Ravi", "Facebook User registered message : "+msg);
		Gson gson = new Gson();
		FacebookUserRegisteredMessage facebookUserRegisteredMessage = gson.fromJson(msg, FacebookUserRegisteredMessage.class);
    	UserProfileUtil.onUserRegistered(context,facebookUserRegisteredMessage);
    }
    private void onDeviceRegistration(Context context,String msg){
    	Log.i("Ravi", "Device registered message : "+msg);
		Gson gson = new Gson();
		DeviceRegisteredMessage deviceRegisteredMessage = gson.fromJson(msg, DeviceRegisteredMessage.class);
    	GcmUtil.deviceRegisteredSuccesfully(context, deviceRegisteredMessage.getDeviceRegId());
    }
    private void onNewFacebookMessage(Context context,String msg,String msgType,String preferenceKey,String vibrationKey){
    	Log.i("Ravi", "New Facebook message : "+msg);
		Gson gson = new Gson();
		NewFacebookNotificationMessage newFacebookNotificationMessage = gson.fromJson(msg, NewFacebookNotificationMessage.class);
		sendForwardNotification(newFacebookNotificationMessage.getNotificationTitle(),"AAP Facebook Update",msgType,preferenceKey,FacebookFeedActivity.class);
    	//FacebookUtil.onFacebookUserRegistered(context,facebookUserRegisteredMessage);
    }
    private <T extends Activity> void sendForwardNotification(String msg,String contentTitle,String msgType,String preferenceKey,Class<T> forwardActivity) {
        mNotificationManager = (NotificationManager)
                ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        
        Intent targetIntent = new Intent(ctx, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("msg", msg);
        bundle.putSerializable("msgType", msgType);
        bundle.putBoolean("Forward", true);
        //Class<FacebookFeedActivity> forwardActivity = FacebookFeedActivity.class;
        bundle.putSerializable("ForwardActivity", forwardActivity);
        targetIntent.putExtra("NotificationMessage", bundle);
        
        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,targetIntent, 0);
        String notificationMessage = msg;
        try {
  		JSONObject jsonObject = new JSONObject(msg);
  		notificationMessage = jsonObject.getString("notificationTitle");
  		
  	} catch (JSONException e) {
  		e.printStackTrace();
  	}
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(contentTitle)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage))
                .setContentText(notificationMessage);
                
        boolean notificationAllowed = PreferencesUtil.getInstance().getBooleanSetting(ctx, preferenceKey, false);
        Log.i("Ravi", "notificationAllowed="+notificationAllowed);
        if(notificationAllowed ){
        	vibratate(ctx, preferenceKey+"_vibrate");
        	Log.i("Ravi", "preferenceKey="+preferenceKey);
            Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            if(preferenceKey != null && !preferenceKey.trim().isEmpty()){
            	String ringToneKey = preferenceKey +"_ringtone";
            	Log.i("Ravi", "ringToneKey="+ringToneKey);
            	String ringTone = PreferencesUtil.getInstance().getStringSetting(ctx, ringToneKey, "DEFAULT_SOUND");
            	Log.i("Ravi", "ringTone="+ringTone);
            	soundUri = Uri.parse(ringTone);
            }
            mBuilder.setSound(soundUri);
        }
        
        
        
        
        
       mBuilder.setContentIntent(contentIntent);
       mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
      }
    // Put the GCM message into a notification and post it.
    private void sendNotification(String msg, String contentTitle,String msgType,String preferenceKey) {
      mNotificationManager = (NotificationManager)
              ctx.getSystemService(Context.NOTIFICATION_SERVICE);
      
      Intent targetIntent = new Intent(ctx, MainActivity.class);
      Bundle bundle = new Bundle();
      bundle.putSerializable("msg", msg);
      bundle.putString("msgType", msgType);
      targetIntent.putExtra("NotificationMessage", bundle);
      PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,targetIntent, 0);
      String notificationMessage = msg;
      try {
		JSONObject jsonObject = new JSONObject(msg);
		notificationMessage = jsonObject.getString("notificationTitle");
		
	} catch (JSONException e) {
		e.printStackTrace();
	}
      NotificationCompat.Builder mBuilder =
              new NotificationCompat.Builder(ctx)
              .setSmallIcon(R.drawable.ic_launcher)
              .setContentTitle(contentTitle)
              .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage))
              .setContentText(notificationMessage);
      boolean notificationAllowed = PreferencesUtil.getInstance().getBooleanSetting(ctx, preferenceKey, false);
      if(notificationAllowed ){
      	vibratate(ctx, preferenceKey+"_vibrate");
          Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          if(preferenceKey != null && !preferenceKey.trim().isEmpty()){
        	  String ringToneKey = preferenceKey +"_ringtone";
          	String ringTone = PreferencesUtil.getInstance().getStringSetting(ctx, ringToneKey, "DEFAULT_SOUND");
          	soundUri = Uri.parse(ringTone);
          }
          mBuilder.setSound(soundUri);
      }
      /*
      Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      Log.i("Ravi", "ringtoneKey="+ringtoneKey);
      if(ringtoneKey != null && !ringtoneKey.trim().isEmpty()){
    	String ringTone = PreferencesUtil.getInstance().getStringSetting(ctx, ringtoneKey, "DEFAULT_SOUND");
    	Log.i("Ravi", "ringTone="+ringTone);
      	soundUri = Uri.parse(ringTone);
      	*/
      
     mBuilder.setContentIntent(contentIntent);
     mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
    
    private void vibratate(Context context,String key){
    	try{
    		Log.i("Ravi", "vibrate Key ="+key);
    		boolean vibrate = PreferencesUtil.getInstance().getBooleanSetting(context, key, true);
    		Log.i("Ravi", "vibrate="+vibrate);
    		if(vibrate){
        		Vibrator v2 = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        		// Vibrate for 500 milliseconds
        		v2.vibrate(200);
    		}
    	}catch(Exception ex){
    		
    	}

    }
    
    
}
